package com.itheima.reggie.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.pojo.Employee;
import com.itheima.reggie.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取员工的登录信息
        Employee employee = (Employee) request.getSession().getAttribute("employee");
        // 判断员工是否已登录
        if (employee != null) {
            // 员工登录后本地线程保存员工id
            BaseContext.setCurrentId(employee.getId());
            return true;
        }
        // 获取用户登录信息
        User user = (User) request.getSession().getAttribute("user");
        // 判断用户是否登录
        if (user != null) {
            // 用户登录后本地线程保存用户id
            BaseContext.setCurrentId(user.getId());
            return true;
        }
        // 未登录响应code=0,msg=NOTLOGIN
        objectMapper.writeValue(response.getWriter(), R.error("NOTLOGIN"));
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 线程结束之后清除本地线程中存储的数据
        BaseContext.removeCurrentId();
    }
}
